﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VBFOOL.MediaPlayer.Core.Interface;
using LibEBML.Common;
namespace VBFOOL.MediaPlayer.MKV
{
    class SimpleSubtitleReader : ISubtitleReader
    {
        internal SimpleSubtitleReader(Matroska document, TrackEntry track)
        {
            this.Track = track;
            this.Document = document;
        }
        public TrackEntry Track { get; private set; }
        public Matroska Document { get; private set; }

        public SubtitleItem this[TimeSpan TimeCode]
        {
            get { return Items.FirstOrDefault(m => m.TimeCode >= TimeCode); }
        }
        public SubtitleItem this[int Index]
        {
            get
            {
                if (Items != null)
                {
                    return m_Subtitles[Index];
                }
                else
                {
                    return null;
                }
            }
        }
        List<SubtitleItem> m_Subtitles = null;
        public IEnumerable<SubtitleItem> Items
        {
            get
            {
                if (m_Subtitles == null)
                {
                    m_Subtitles = new List<SubtitleItem>();
                    var timecodescale = Document.Segment.Info.TimecodeScale / 100;
                    foreach (var cluster in Document.Segment.Clusters)
                    {
                        foreach (var b in cluster.Blocks.Where(m => m.TrackNumber == Track.TrackNumber))
                        {
                            SubtitleItem item = new SubtitleItem();
                            var ms = b.GetBlockData(null);
                            item.Text = string.Join(Environment.NewLine, ms.Select(m => System.Text.Encoding.UTF8.GetString(m, 0, m.Length)));
                            item.TimeCode = TimeSpan.FromTicks((cluster.TimeCode + b.TimeCode) * timecodescale);
                            if (b is Block)
                            {
                                var d = (b as Block).BlockDuration;
                                if (d > 0)
                                {
                                    item.Duration = TimeSpan.FromTicks(d * timecodescale);
                                }
                                else
                                {
                                    item.Duration = TimeSpan.FromTicks(Track.DefaultDuration / 100);
                                }
                            }
                            m_Subtitles.Add(item);
                        }
                    }
                }
                return m_Subtitles;
            }
        }
    }
}
